package logic

import (
	"context"
	"fmt"
	"good_srv/cache"
	"good_srv/models"

	"good_srv/good"
	"good_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录接口
func (l *LoginLogic) Login(in *good.LoginRequest) (*good.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var users models.User

	if in.Phone == "" && in.Account == "" {
		logx.Error("请选择一种登录方式")
		return nil, fmt.Errorf("请选择一种登录方式")
	}
	if in.Phone != "" {
		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
		if result != in.SendCode {
			return nil, fmt.Errorf("验证码失效")
		}
		models.DB.Where("phone=?", in.Phone).Find(&users)
		if users.ID == 0 {
			logx.Error("当前用户未注册")
			return nil, fmt.Errorf("当前用户未注册")
		}
		if users.StatusId == 1 {
			logx.Error("当前用户手机号异常不能登录")
			return nil, fmt.Errorf("当前用户手机号异常不能登录")
		}
	}
	if in.Account != "" {
		models.DB.Where("account=?", in.Account).Find(&users)
		if users.ID == 0 {
			logx.Error("当前用户未注册")
			return nil, fmt.Errorf("当前用户未注册")
		} else {
			if users.Password != in.Password {
				logx.Error("密码不正确")
				return nil, fmt.Errorf("密码不正确")
			}
		}
	}
	return &good.LoginResponse{
		Id: int64(users.ID),
	}, nil
}
